<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 
 * 后台系统设置控制器
 * @author 66diqiu-li
 *
 */
class Admin_Shopconfig_module extends CI_Module {
	
	/**
     * 站点配置ID
     * @var string
	 */
    private $sid = '';

    public function __construct(){
    	parent::__construct();
        $this->sid = $GLOBALS['sid'] ;
    	$this->load->model('admin.Shopconfig_model');
        $this->load->model('admin.area_model');
        $this->load->model('admin.Upload_model');
        $this->load->model('admin.Site_model');
        $this->load->model('admin.Adminuser_model');
        $this->Adminuser_model->is_login();
    }
    
	/**
	 * 
	 * 系统设置列表
	 */
    function index(){
        $result = $this->Shopconfig_model->get_list($this->sid);
        $data['row'] = $result;
        $data['sid'] = $this->sid;
        $data['site_list'] = array();
        $data['conn_site_list'] = array();
        if($result['dis_sites']['value']){
            $data['site_list'] = $this->Site_model->get_site_list(1,$result['dis_sites']['value']);
        }
        if($result['conn_sites']['value']){
            $data['conn_site_list'] =  $this->Site_model->get_site_list(1,$result['conn_sites']['value']);
        }

        if($result['depart_citys']['value']){
            $data['depart_citys_list'] = $this->area_model->get_area_name(array($result['depart_citys']['value']),false);;
        }

        //是否为超全局管理员
        $id = $this->session->userdata('admin_user_id');
        $data['admin_row'] = $this->Adminuser_model->get_row(array('id'=>$id,'sid'=>'-1'),'sid');
        $data['is_sub'] = $this->Shopconfig_model->check_site($this->sid);

        $data['form_post']  = site_url('admin/shopconfig/save');
        $this->load->view('shopconfig/shopconfig',$data);
    }
    
    /**
     * 
     * 系统设置保存操作
     */
    function save(){
        $form = $this->input->post('Form');
        $other = $this->input->post('other');
//        $form['dis_sites'] = empty($form['dis_sites'])?'':implode(",",$form['dis_sites']);
        $res = $this->Shopconfig_model->update_batch($other['sid'],$form);

        if($res){
            if($form['sitename']){
                $this->Site_model->edit_row(array('name'=>$form['sitename']),array('sid'=>$GLOBALS['sid']));
            }
            $shop_config = $this->Shopconfig_model->get_info($GLOBALS['sid']);
            $shop_config = $this->Shopconfig_model->set_basice_info($shop_config);
            $GLOBALS['config'] = $shop_config;
            unset($shop_config);
            /*
            $this->_save_image_lib_settings_to_file($other);
            */
            $this->success('系统配置保存成功!',site_url('admin/shopconfig/index'),true);
        }else{
        	$this->error('系统配置保存失败!',site_url('admin/shopconfig/index'),true);
        }
    }

    /**
     *
     * 系统设置保存LOGO操作
     */
    public function save_logo(){

        //上传配置文件
        $config = $this->Upload_model->upload_config();
        $this->load->library('upload',$config);
        $absolute_path = str_replace('\\', '/', getcwd()).'/';
        if ( ! $this->upload->do_upload('file'))
        {
            $error = array('error' => $this->upload->display_errors());
            $this->error($error['error'],'',true);
        }else
        {
            $data = array('upload_data' => $this->upload->data());
            $message = str_replace($absolute_path, '', $data['upload_data']['full_path']);
            $file_ext = $data['upload_data']['file_ext'] ;
            $des_url = '/uploads/'.$GLOBALS['sid'].'/logo'.$file_ext ;
            $des = getcwd().$des_url;
            if(copy($message,$des))
            {
                if(unlink($message))
                {
                    $new_url = substr($des_url,1);;
                    $array = array('sitelogo'=>URLPIC.$new_url);
                    $res = $this->Shopconfig_model->update_batch($this->sid,$array);
                }
            }

            //上传到FTP
            $this->Upload_model->ftp_upload($new_url);
            $this->success(URLPIC.$new_url,'',true);
        }
    }

    /**
     *
     * 系统设置保存微信二维码操作
     */
    public function save_wx_qr(){

        //上传配置文件
        $config = $this->Upload_model->upload_config();
        $this->load->library('upload',$config);
        $absolute_path = str_replace('\\', '/', getcwd()).'/';
        if ( ! $this->upload->do_upload('file'))
        {
            $error = array('error' => $this->upload->display_errors());
            $this->error($error['error'],'',true);
        }else
        {
            $data = array('upload_data' => $this->upload->data());
            $message = str_replace($absolute_path, '', $data['upload_data']['full_path']);
            $file_ext = $data['upload_data']['file_ext'] ;
            $des_url = '/uploads/'.$GLOBALS['sid'].'/wx_qr'.$file_ext ;
            $des = getcwd().$des_url;
            if(copy($message,$des))
            {
                if(unlink($message))
                {
                    $new_url = substr($des_url,1);;
                    $array = array('site_wx_qr'=>URLPIC.$new_url);
                    $res = $this->Shopconfig_model->update_batch($this->sid,$array);
                }
            }

            //上传到FTP
            $this->Upload_model->ftp_upload($new_url);
            $this->success(URLPIC.$new_url,'',true);
        }
    }
    /**
     *
     * 系统设置保存微博二维码操作
     */
    public function save_wb_qr(){

        //上传配置文件
        $config = $this->Upload_model->upload_config();
        $this->load->library('upload',$config);
        $absolute_path = str_replace('\\', '/', getcwd()).'/';
        if ( ! $this->upload->do_upload('file'))
        {
            $error = array('error' => $this->upload->display_errors());
            $this->error($error['error'],'',true);
        }else
        {
            $data = array('upload_data' => $this->upload->data());
            $message = str_replace($absolute_path, '', $data['upload_data']['full_path']);
            $file_ext = $data['upload_data']['file_ext'] ;
            $des_url = '/uploads/'.$GLOBALS['sid'].'/weibo_qrcode'.$file_ext ;
            $des = getcwd().$des_url;
            if(copy($message,$des))
            {
                if(unlink($message))
                {
                    $new_url = substr($des_url,1);;
                    $array = array('weibo_qrcode'=>URLPIC.$new_url);
                    $res = $this->Shopconfig_model->update_batch($this->sid,$array);
                }
            }

            //上传到FTP
            $this->Upload_model->ftp_upload($new_url);
            $this->success(URLPIC.$new_url,'',true);
        }
    }


    /**
     *
     * 系统设置保存ICO图标操作
     */
    public function save_ico(){

        //上传配置文件
        $config = $this->Upload_model->upload_config();
        $this->load->library('upload',$config);
        $absolute_path = str_replace('\\', '/', getcwd()).'/';
        if ( ! $this->upload->do_upload('file'))
        {
            $error = array('error' => $this->upload->display_errors());
            $this->error($error['error'],'',true);
        }else
        {
            $data = array('upload_data' => $this->upload->data());
            $message = str_replace($absolute_path, '', $data['upload_data']['full_path']);
            $file_ext = $data['upload_data']['file_ext'] ;
            $des_url = '/uploads/'.$GLOBALS['sid'].'/favicon'.$file_ext ;
            $des = getcwd().$des_url;
            if(copy($message,$des))
            {
                if(unlink($message))
                {
                    $new_url = substr($des_url,1);;
                    $array = array('site_ico'=>URLPIC.$new_url);
                    $res = $this->Shopconfig_model->update_batch($this->sid,$array);
                }
            }

            //上传到FTP
            $this->Upload_model->ftp_upload($new_url);
            $this->success(URLPIC.$new_url,'',true);
        }
    }

    /**
     *
     * 系统设置保存银联支付证书操作
     */
    public function save_unionpay_cert($path=''){

        if(isset($path) && ! empty($path)) {
            $path = $path . $GLOBALS['sid'] . '/';
        }
        else {
            $path = './application/libraries/unionpay/cert/' . $GLOBALS['sid'] . '/';
        }
        $uploadallowext = '*';
        $uploadmaxsize = isset($GLOBALS['config']['uploadmaxsize']) ? $GLOBALS['config']['uploadmaxsize'] : '20240';
        $config['upload_path'] = $path;
        $config['allowed_types'] = $uploadallowext;
        $config['overwrite'] = TRUE;
        $config['max_size'] = $uploadmaxsize;
        $config['max_width'] = '0';
        $config['max_height'] = '0';
        $config['max_filename'] = '0';
        $config['encrypt_name'] = FALSE;
        $config['remove_spaces'] = TRUE;
        if (!is_dir($config['upload_path'])) {
            dmkdir($config['upload_path'], 0777);
        }

        $this->load->library('upload',$config);
        $absolute_path = str_replace('\\', '/', getcwd()).'/';
        if ( ! $this->upload->do_upload('file'))
        {
            $error = array('error' => $this->upload->display_errors());
            $this->error($error['error'],'',true);
        }else
        {
            /*
            $data = array('upload_data' => $this->upload->data());
            $array = array('site_ico'=>URLPIC.$new_url);
            $res = $this->Shopconfig_model->update_batch($this->sid,$array);
            */
            $file_path = $this->upload->data();
            $cert_file = './' . ltrim($file_path['full_path'],BASEPATH);
            $this->success($cert_file,'',true);
        }
    }

    /**
     * 保存图片水印配置到图片处理配置文件
     * @param $data
     */
    private function _save_image_lib_settings_to_file($data){

        //是否开启水印
        if($data['watermarkenable']==1){
            //水印图像位置
            switch($data['watermarkpos']){
                case '1':
                    $wm_vrt_alignment = 'top';
                    $wm_hor_alignment = 'left';
                    break;
                case '2':
                    $wm_vrt_alignment = 'top';
                    $wm_hor_alignment = 'center';
                    break;
                case '3':
                    $wm_vrt_alignment = 'top';
                    $wm_hor_alignment = 'right';
                    break;
                case '4':
                    $wm_vrt_alignment = 'middle';
                    $wm_hor_alignment = 'left';
                    break;
                case '5':
                    $wm_vrt_alignment = 'middle';
                    $wm_hor_alignment = 'center';
                    break;
                case '6':
                    $wm_vrt_alignment = 'middle';
                    $wm_hor_alignment = 'right';
                    break;
                case '7':
                    $wm_vrt_alignment = 'bottom';
                    $wm_hor_alignment = 'left';
                    break;
                case '8':
                    $wm_vrt_alignment = 'bottom';
                    $wm_hor_alignment = 'center';
                    break;
                case '9':
                    $wm_vrt_alignment = 'bottom';
                    $wm_hor_alignment = 'right';
                    break;
                default:
                    $wm_vrt_alignment = 'top';
                    $wm_hor_alignment = 'left';
                    break;
    }

            // files start
            $conf  = "<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');\n\n";
            $conf .= "\$config['wm_type'] = 'overlay';\n";
            $conf .= "\$config['quality'] = '".$data['watermarkquality']."';\n";
            $conf .= "\$config['wm_overlay_path'] = '".$data['watermarkimg']."';\n";
            $conf .= "\$config['wm_opacity'] = '".$data['watermarkpct']."';\n";
            $conf .= "\$config['wm_vrt_alignment'] = '".$wm_vrt_alignment."';\n";
            $conf .= "\$config['wm_hor_alignment'] = '".$wm_hor_alignment."';\n";
            // files end
            $conf .= "\n";
            $conf .= '/* End of file image_lib.php */'."\n";
            $conf .= '/* Auto generated by update on '. date('Y.m.d H:i:s') .' */'."\n";
            $conf .= '/* Location: ./application/config/image_lib.php */'."\n";

            return @file_put_contents(APPPATH . '/config/image_lib' . EXT, $conf);
        }
    }

    /*
  * 选择站点
  * */
    public function site_list(){
        $arg_post = $this->input->get_post();
        $condition = array();
        $condition['province'] =  $this->input->get_post('province');
        $condition['city'] = $this->input->get_post('city');
        $condition['name'] = addslashes($this->input->get_post('name'));
        $condition['url'] = addslashes($this->input->get_post('url'));

        $dis_sites = trim($this->sid.','.$GLOBALS['config']['dis_sites'],',');
        $conn_sites = trim($this->sid.','.$GLOBALS['config']['conn_sites'],',');
        $disable =  $this->input->get_post('disable');
        $data['disable'] = empty($disable)?0:$disable;

        $where = "";
        if($dis_sites&&$disable==0){
            $where .= " and a.sid not in ($dis_sites)";
        }
        if($conn_sites&&$disable==1){
            $where .= " and a.sid not in ($conn_sites)";
        }
        if($condition['province']>0){
            $where.= " and b.key_value=".$condition['province'];
        }
        if($condition['city']>0){
            $where .= " and c.key_value=".$condition['city'];
        }
        if($condition['url']){
            $where .= " and a.url like '%".$condition['url']."%'";
        }
        if($condition['name']){
            $where.= " and a.name like '%".$condition['name']."%'";
        }

        $page_config['perpage'] =10;   //每页条数
        $page_config['url']     ='admin/shopconfig/site_list';//url
        $page_config['param'] = '?province='.$condition['province'].'&city='.$condition['city'].'&url='.$condition['url'].'&name='.$condition['name'];//参数
        $page_config['seg']     =4;//参数取 index.php之后的段数，默认为3，即index.php/control/function/18 这种形式
        $page_config['nowindex']=$this->uri->segment($page_config['seg']) ? $this->uri->segment($page_config['seg']):1;//当前页
        $res  = $this->Site_model->get_list($page_config['perpage'],$page_config['nowindex'],$where);
        $page_config['total']  = $res['count'];
        $this->load->library('mypageclass');
        $this->mypageclass->initialize($page_config);

        $data['condition'] = $condition;
        $data['list'] = $res['list'];
        $data['form_url'] = site_url('/admin/shopconfig/site_list');
        $this->load->view('/shopconfig/site_list',$data);
    }


    /*
     * 出发城市
     *
     * */

    public function depart_list(){

        $result = $this->Shopconfig_model->get_list($this->sid);
         if($result['depart_citys']['value']){
             $data['depart_citys_list'] = $this->area_model->get_area_name(array($result['depart_citys']['value']),false);;
        }
        $this->load->view('/shopconfig/depart_list',$data);

    }

    function  sel_depart_list(){
        $post_data = $this->input->post();
        $result = $this->Shopconfig_model->get_list($this->sid);

         if(strpos($result['depart_citys']['value'],SITECITY)===false)
         {
             $cityids_string = SITECITY.''.$result['depart_citys']['value'].','.$post_data['cityids'];
         }
         else
         {
             $cityids_string = $result['depart_citys']['value'].','.$post_data['cityids'];
         }

        $cityids = implode(",",array_filter(array_unique(explode(",",$cityids_string))));
        $list = $this->area_model->get_area_name(array($cityids),false);
        $content = '';
        foreach ($list as $key=>$val) {
            $content .= '<span>'.$val.'<a class="del" alt="'.$key.'"></a></span>';
        }
        $data = array();
        $data['cityids'] = $cityids;
        $data['content']= $content;
        $this->ajaxReturn($data);

    }


    function  sel_list(){
        $post_data = $this->input->post();

        $sids = implode(",", array_filter(array_unique(explode(",",$post_data['sids'].$post_data['sids'].',0'))));
        $sids = rtrim($sids,",");
        $list = $this->Site_model->get_site_list(1,$sids);
        if($GLOBALS['sid']==42){
            print_r($list);exit;
        }
        $content = '';
        foreach ($list as $val) {
            $content .= '<span>'.$val['name'].'<a class="del" alt="'.$val['sid'].'"></a></span>';
        }
        $data = array();
        $data['sids'] = $sids;
        $data['content']= $content;
        $this->ajaxReturn($data);

    }

}